import axios from 'axios';
import errorCode from '@/utils/errorCode';
import { tansParams, blobValidate } from '@/utils/utils';
import { saveAs } from 'file-saver';
import { ElMessage, ElLoading } from 'element-plus';

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 10000,
});
service.interceptors.request.use(
  (arg) => {
    const config = arg;
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Token = token;
    }

    // get请求映射params参数
    if (config.method === 'get' && config.params) {
      // eslint-disable-next-line prefer-template
      let url = config.url + '?' + tansParams(config.params);
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }
    if (config.FormData) {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  },
);

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;

    // 二进制数据则直接返回
    if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
      return res.data;
    }
    if (code === 200) {
      return res.data;
    }
    if (code !== 200) {
      // 获取错误信息
      const msg = errorCode[code] || res.data.msg || errorCode.default;
      ElMessage({
        message: msg,
        type: 'error',
      });
      return Promise.reject(new Error(res));
    }
  },
  (error) => {
    let msg = '系统异常';
    if (error.response && error.response.data && typeof error.response.data.message === 'string') {
      msg = error.response.data.message;
    }
    ElMessage({
      message: msg,
      type: 'error',
    });
    return Promise.reject(error);
  },
);

// 通用下载方法
export function download(url, params, filename, config) {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在下载数据，请稍候',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  const projectId = localStorage.getItem('projectId');
  const token = localStorage.getItem('token');
  return service
    .post(url, params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Proid: projectId,
        Token: token,
      },
      responseType: 'blob',
      timeout: 10000000,
      ...config,
    })
    .then(async (data) => {
      const isBlob = blobValidate(data);
      if (isBlob) {
        const blob = new Blob([data]);
        saveAs(blob, filename);
      } else {
        loadingInstance.close();
      }
    })
    .catch((err) => {
      ElMessage({
        message: err.msg || '下载文件出现错误，请联系管理员！',
        type: 'error',
      });
      loadingInstance.close();
    });
}
export default service;
